package main

import (
	"context"
	"log"
	"strconv"
	"time"

	etcd "github.com/coreos/etcd/client"
)

type Worker struct {
	etcd.KeysAPI

	Path string
	Host string
	Load int
}

func NewWorker(hosts []string, addr string, path string) (*Worker, error) {
	config := etcd.Config{
		Endpoints: hosts,
		Transport: etcd.DefaultTransport,
		// fail fast when the target endpoint is unavailable
		HeaderTimeoutPerRequest: time.Second,
	}

	clt, err := etcd.New(config)
	if err != nil {
		return nil, err
	}

	worker := &Worker{
		KeysAPI: etcd.NewKeysAPI(clt),

		Path: path,
		Host: addr,
		Load: 0,
	}
	return worker, nil
}

func (this *Worker) HeartBeat() {
	for {
		_, err := this.Set(context.Background(), this.Path+"/"+this.Host, strconv.Itoa(this.Load), &etcd.SetOptions{
			TTL: time.Second * 2,
		})

		if err != nil {
			log.Println("Error update workerInfo:", err)
		}

		time.Sleep(time.Second * 3)
	}
}
